<template>
	<view class="LuYin" v-show="diaShow" @tap.stop="handleTapModal">
		<view :class="['MyDialog-LuYin', recordingSrc ? 'h86' : '']" @tap.stop="" :style="style">
			<view class="time">{{ recordingTime ? recordingTime : "00:00:00.00" }}</view>
			<view class="ly-box" @tap="recording">
				<image class="ly-svg" :src="imgPath + 'createAvatar/luyin-big.svg'" mode="widthFix"></image>
			</view>
			<view class="tips-text">点击{{ recordingText }}录音</view>
			<audio class="recordingPlay" :src="recordingSrc" controls v-show="recordingSrc"></audio>
			<view class="btns-list">
				<view class="btn-item" @tap="openUploadShow">
					<!-- <image class="icon" src="" mode=""></image> -->
					<view class="text">本地音频</view>
				</view>
				<view class="btn-item" v-if="recordingSrc" @tap="join">
					<!-- <image class="icon" src="" mode=""></image> -->
					<view class="text">应用</view>
				</view>
			</view>
			<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="14" height="14" viewBox="0 0 14 14" fill="none" class="close" @tap="close">
				<path fill-rule="evenodd" fill="#999999" d="M12.76 0L7 5.76L1.24 0L0 1.24L5.76 7L0 12.76L1.24 14L7 8.24L12.76 14L14 12.76L8.24 7L14 1.24L12.76 0Z"></path>
			</svg>
		</view>
		<view class="MyDialog-upload" @tap.stop="" :style="style2">
			<view class="btns-list">
				<view class="item" v-for="(item, index) in btnOpt" :key="index" @tap="dynamicEvents(item.fnName)">
					<view class="text">{{ item.text }}</view>
				</view>
			</view>
			<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="14" height="14" viewBox="0 0 14 14" fill="none" class="close" @tap="close2">
				<path fill-rule="evenodd" fill="#999999" d="M12.76 0L7 5.76L1.24 0L0 1.24L5.76 7L0 12.76L1.24 14L7 8.24L12.76 14L14 12.76L8.24 7L14 1.24L12.76 0Z"></path>
			</svg>
		</view>
		<RecorderCore ref="RecorderCore" v-show="0"></RecorderCore>
	</view>
</template>

<script>
import { tools } from "@/utils/util";
import * as api from "@/api/createVideo.js";
import axios from "axios";
import RecorderCore from "@/components/RecorderCore/RecorderCore.vue";
export default {
	name: "LuYin",
	props: {
		show: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			imgPath: tools.imgPath,
			mediaRecorder: {
				state: ""
			},
			recordingTimer: null,
			recordingTime: 0,
			recordingText: "开始",
			recordingSrc: "",
			recordingPlaying: false,
			diaShow: false,
			uploadShow: false,
			style: {
				transform: "translateY(100%)"
			},
			style2: {
				transform: "translateY(100%)"
			},
			uploadFileSize: 200,
			btnOpt: [
				{
					text: "上传音频",
					fnName: "uploadFile"
				},
				{
					text: "视频提取",
					fnName: "getVideo"
				}
			]
		};
	},
	created() {},
	mounted() {
		this.initHandle();
	},
	methods: {
		// 事件初始化
		initHandle() {
			const that = this;
			document.querySelector(".MyDialog-LuYin").ontransitionend = function (evnet) {
				let result = evnet.target.style?.transform?.match(/translateY\((.*)\)/);
				if (!that.uploadShow && result && result[1] == "100%") {
					that.diaShow = false;
				}
			};
			let recordingPlay = document.querySelector(".recordingPlay audio");
			recordingPlay.ondurationchange = function (evnet) {
				console.log("ondurationchange");
				that.recordingTime = tools.seconds2time(this.duration);
			};
			recordingPlay.onplay = function (evnet) {
				that.recordingPlaying = true;
			};
			recordingPlay.onpause = function (evnet) {
				that.recordingPlaying = false;
			};
			recordingPlay.onended = function (evnet) {
				that.recordingPlaying = false;
			};
		},
		// 打开上传界面
		openUploadShow() {
			this.stopPlaying();
			if (this.mediaRecorder.state == "recording") {
				this.recording();
			}
			this.uploadShow = true;
		},
		// 应用
		join() {
			this.$emit("join", this.recordingSrc);
			this.close();
		},
		// 停止试听
		stopPlaying() {
			let recordingPlay = document.querySelector(".recordingPlay audio");
			recordingPlay.pause();
			recordingPlay.currentTime = 0;
		},
		// 录音
		async recording() {
			//录音
			const that = this;

			if (that.recordingPlaying) {
				this.stopPlaying();
			}
			if (that.mediaRecorder.state != "recording") {
				//开始录音
				let flag = await that.$refs.RecorderCore.recStart();
				if (!flag) return (this.mediaRecorder.state = "");
				let nowTime = new Date().getTime();
				that.recordingTimer = setInterval(() => {
					// that.recordingTime = ((new Date().getTime() - nowTime) / 1000);
					that.recordingTime = tools.seconds2time(that.$refs.RecorderCore.duration / 1000);
				}, 1000 / 60);
				that.mediaRecorder.state = "recording";
				that.recordingText = "结束";
			} else {
				//停止录音
				let flag = await that.$refs.RecorderCore.recStop();
				if (!flag) return;
				clearInterval(that.recordingTimer);
				that.recordingTimer = null;
				that.mediaRecorder.state = "";
				that.recordingText = "开始";
				let blob = this.$refs.RecorderCore.logs[0].res.blob;
				let tempSrc = URL.createObjectURL(blob);
				console.log("停止录音");
				let matterValue = await tools.setVideoSrc(tempSrc);
				let name = new Date().getTime();
				let fileOfBlob = new File([blob], name, {
					type: "audio/wav"
				});
				let ossData = await api.postOSS({
					reqType: "mat_audio",
					matName: name,
					payLoad: { matterValue: matterValue }
				});
				let res = await this.getOSSApi_new(ossData, fileOfBlob, name);
				console.log(res);
				// let res = await that.getOSSApi(fileOfBlob, name);
				if (res?.src) {
					that.recordingSrc = res.src;
				}
			}
		},
		// 动态事件
		dynamicEvents(fnName) {
			if (tools.myTypeOf(this[fnName]) == "Function") {
				this[fnName]();
			} else {
				throw `${fnName}不是一个函数`;
			}
		},
		// 上传音频
		uploadFile() {
			const that = this;
			uni.chooseFile({
				count: 1, //默认100
				extension: [".wav", ".mp3", ".m4a", ".wma", ".aac", ".ogg", "3gpp"],
				success: async function (res) {
					let file = res.tempFiles[0];
					if (!file.type.includes("audio")) {
						return tools.easyToast("请选择音频文件！");
					}
					let name = file.name;
					if (!/^[\u4e00-\u9fa5a-zA-Z0-9\.\-]+$/.test(name)) {
						return tools.easyToast("文件名不能包含符号，只能是文字或数字");
					}
					if (file.size / 1024 / 1024 > that.uploadFileSize) {
						return tools.easyToast(`文件大小超过${that.uploadFileSize}M!`);
					}
					let matterValue = await tools.setVideoSrc(res.tempFilePaths[0]);
					if (matterValue < 1) {
						return tools.easyToast("音频时长必须不少于1秒！");
					}
					let ossData = await api.postOSS({
						reqType: "mat_audio",
						matName: name,
						payLoad: { matterValue: matterValue }
					});
					let ress = await that.getOSSApi_new(ossData, file, name);
					if (!ress) {
						tools.easyToast("上传失败！");
						return;
					}
					console.log("上传音频", ress);
					that.recordingSrc = ress.src;
					that.close2();
				}
			});
		},
		//上传文件api
		async getOSSApi_new(ossData, file, name) {
			const that = this;
			let res = ossData;

			function getUUID() {
				let keyStr = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
				keyStr = "xxxxxxxx-6xxx";
				return keyStr.replace(/[xy]/g, (c) => {
					return (c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8").toString(16);
				});
			}
			const formData = new FormData();
			let url_name = "https://alleymall.oss-cn-guangzhou.aliyuncs.com";
			let key = res.data.dir + "/" + getUUID() + name;
			formData.append("policy", res.data.policy);
			formData.append("signature", res.data.signature);
			formData.append("ossaccessKeyId", res.data.accessid);
			formData.append("key", key);
			formData.append("dir", res.data.dir);
			formData.append("host", res.data.host);
			formData.append("expire", res.data.expire);
			formData.append("callback", res.data.callback);
			// formData.append('type', res.data.callback)
			formData.append("file", file);

			return axios
				.post(url_name, formData, {
					headers: {
						"Content-Type": "multipart/form-data"
					}
				})
				.then((response) => {
					let src = url_name + "/" + key;
					// console.log(src);
					// that.audioPlayerSrc = src;
					// console.log(response);
					return {
						...response,
						src
					};
				})
				.catch((error) => {
					console.log(error);
				});
		},

		// 视频提取
		getVideo() {
			console.log("视频提取");
			tools.easyToast("暂未开放！");
		},
		// 关闭录音界面
		close() {
			this.stopPlaying();
			if (this.mediaRecorder.state == "recording") {
				this.recording();
			}
			this.$emit("close");
		},
		// 关闭音频上传界面
		close2() {
			this.uploadShow = false;
			this.style.transform = `translateY(0%)`;
		},
		// 监听遮罩层tap事件
		handleTapModal() {
			if (this.uploadShow) {
				this.close2();
			} else {
				this.close();
			}
		}
	},
	watch: {
		show: {
			handler(val) {
				if (val) {
					this.diaShow = true;
					setTimeout(() => {
						this.style.transform = `translateY(0%)`;
					}, 168);
				} else {
					this.style.transform = `translateY(100%)`;
				}
			}
		},
		uploadShow: {
			handler(val) {
				if (val) {
					setTimeout(() => {
						this.style2.transform = `translateY(0%)`;
						this.style.transform = `translateY(100%)`;
					}, 168);
				} else {
					this.style2.transform = `translateY(100%)`;
				}
			}
		}
	},
	components: {
		RecorderCore
	}
};
</script>

<style lang="scss">
.LuYin {
	width: 100vw;
	height: 100vh;
	overflow: hidden;
	position: absolute;
	left: 0vw;
	right: 0vw;
	background: rgba(0, 0, 0, 0.68);
	z-index: 106;

	.close {
		position: absolute;
		top: 2vw;
		right: 2vw;
	}

	.MyDialog-LuYin {
		width: 100%;
		height: 68vw;
		position: absolute;
		bottom: 0vw;
		background: #fff;
		color: #000;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 6vw 2vw;
		padding-top: 2vw;
		box-sizing: border-box;
		border-radius: 2.5vw 2.5vw 0vw 0vw;
		transition: all 300ms;

		&.h86 {
			height: 86vw;
		}

		.time {
			margin: 2vw;
		}

		.ly-box {
			background: linear-gradient(217.51deg, rgba(0, 255, 174, 1) 0%, rgba(27, 161, 250, 1) 100%);
			padding: 2vw;
			width: 20vw;
			height: 20vw;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;

			.ly-svg {
				width: 52%;
			}
		}

		.tips-text {
			padding: 5vw 2vw;
			font-size: 28rpx;
			color: rgba(51, 51, 51, 1);
		}

		.btns-list {
			display: flex;
			justify-content: center;
			align-items: center;

			.btn-item {
				border-radius: 2.5vw;
				background: rgba(237, 237, 237, 1);
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 1.5vw 2vw;
				margin-right: 2vw;

				&:last-child {
					margin-right: 0vw;
				}

				.text {
					font-size: 28rpx;
					color: rgba(102, 102, 102, 1);
				}
			}
		}
	}

	.MyDialog-upload {
		width: 100%;
		height: 32vw;
		position: absolute;
		bottom: 0vw;
		background: #fff;
		color: #000;
		padding: 2vw;
		padding-top: 2vw;
		box-sizing: border-box;
		border-radius: 2.5vw 2.5vw 0vw 0vw;
		transition: all 300ms;

		.btns-list {
			box-sizing: border-box;
			padding: 2vw;
			display: flex;
			flex-direction: column;
			height: 100%;

			.item {
				flex: 1;
				display: flex;
				justify-content: center;
				align-items: center;
				border-bottom: 1px solid rgba(240, 240, 240, 1);

				&:last-child {
					border-bottom: none;
				}
			}
		}
	}
}
</style>
